package com.jun.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jun.pojo.vo.R;
import com.jun.service.SysAdminService;
import com.jun.util.CookieUtil;
import com.jun.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {
  @Autowired
  private ObjectMapper objectMapper;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    log.info("进入拦截器");

    Cookie[] cookies = request.getCookies();
    String token = CookieUtil.getToken(cookies, JwtUtil.COOKIE_KEY);
    if (token == null) {
      log.info("token为空");
      log.info("被拦截");
      writeResponse(response);
      return false;
    }
    String sub = JwtUtil.obtainSubject(token);
    log.info("sub = " + sub);
    if (sub != null) {
      return true;
    } else {
      log.info("被拦截");
      writeResponse(response);
      return false;
    }
  }


  private void writeResponse(HttpServletResponse response) throws IOException {
    R r = new R(500, "login error");
    String json = objectMapper.writeValueAsString(r);

    try (PrintWriter writer = response.getWriter() ) {
      writer.write(json);
      writer.flush();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
